package com.pyp.kuaishou.controller;

import com.pyp.kuaishou.service.KSAuthService;
import com.pyp.kuaishou.service.KSPublishService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;

/**
 * 作者: lauJinyu
 * 控制层：一键发布接口（H5触发后端发布）
 */
@Controller
@RequiredArgsConstructor
public class PublishController {

    private final KSPublishService ksPublishService; // 业务层封装
    private final KSAuthService ksAuthService;       // 用于生成授权URL

    /**
     * 前端H5触发：根据app_id和store_id执行一次发布流程
     * 注意：这个接口需要前端显式传入access_token，后端不做任何缓存/存储
     */
    @GetMapping("/publish")
    public ResponseEntity<?> publish(@RequestParam("app_id") String appId,
                                     @RequestParam("store_id") String storeId,
                                     @RequestParam(value = "access_token", required = false) String accessToken) {
        if (accessToken == null || accessToken.isEmpty()) {
            Map<String, Object> hint = new HashMap<>();
            hint.put("success", false);
            hint.put("message", "缺少access_token。请先完成授权获取access_token，或在请求参数中传入access_token用于一次性发布");
            hint.put("authorize_url", ksAuthService.buildAuthorizeUrl(appId));
            return ResponseEntity.ok(hint);
        }
        // 调用业务层进行发布
        Map<String, Object> result = ksPublishService.publishVideo(accessToken, appId);
        return ResponseEntity.ok(result);
    }
}